package com.ttl.sbgl.loginback.service.serviceImpl;

import com.ttl.sbgl.loginback.entity.QrToken;
import com.ttl.sbgl.loginback.entity.User;
import com.ttl.sbgl.loginback.repository.QrTokenRepository;
import com.ttl.sbgl.loginback.repository.UserRepository;
import com.ttl.sbgl.loginback.service.QrLoginService;
import com.ttl.sbgl.loginback.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class QrLoginServiceImpl implements QrLoginService {

    @Resource
    private QrTokenRepository qrTokenRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private UserService userService;

    @Override
    public QrToken generateQrToken() {
        // 生成唯一的token
        String token = UUID.randomUUID().toString().replace("-", "");
        QrToken qrToken = new QrToken(token);

        // 保存到数据库
        return qrTokenRepository.save(qrToken);
    }

    @Override
    public QrToken checkQrTokenStatus(String token) {
        QrToken qrToken = qrTokenRepository.findByToken(token);
        if (qrToken == null) {
            return null;
        }

        // 检查是否过期
        if (LocalDateTime.now().isAfter(qrToken.getExpireTime())) {
            qrToken.setStatus("EXPIRED");
            qrTokenRepository.save(qrToken);
        }

        return qrToken;
    }

    @Override
    public boolean confirmQrLogin(String token, String userName, String password) {
        QrToken qrToken = qrTokenRepository.findByToken(token);
        if (qrToken == null) {
            return false;
        }

        // 检查是否过期
        if (LocalDateTime.now().isAfter(qrToken.getExpireTime())) {
            qrToken.setStatus("EXPIRED");
            qrTokenRepository.save(qrToken);
            return false;
        }

        // 验证用户登录
        User user = userService.loginService(userName, password);
        if (user == null) {
            return false;
        }

        // 更新token状态
        qrToken.setStatus("CONFIRMED");
        qrToken.setUserName(userName);
        qrTokenRepository.save(qrToken);

        return true;
    }

    @Override
    public User getUserByToken(String token) {
        QrToken qrToken = qrTokenRepository.findByToken(token);
        if (qrToken == null || !"CONFIRMED".equals(qrToken.getStatus())) {
            return null;
        }

        // 获取用户信息
        User user = userRepository.findByName(qrToken.getUserName());
        if (user != null) {
            user.setPassword(""); // 清除密码
        }

        return user;
    }

    @Override
    public boolean confirmQrLoginDirect(String token, String userName) {
        QrToken qrToken = qrTokenRepository.findByToken(token);
        if (qrToken == null) {
            return false;
        }

        // 检查是否过期
        if (LocalDateTime.now().isAfter(qrToken.getExpireTime())) {
            qrToken.setStatus("EXPIRED");
            qrTokenRepository.save(qrToken);
            return false;
        }

        // 验证用户是否存在
        User user = userRepository.findByName(userName);
        if (user == null) {
            return false;
        }

        // 更新token状态（无需密码验证）
        qrToken.setStatus("CONFIRMED");
        qrToken.setUserName(userName);
        qrTokenRepository.save(qrToken);

        return true;
    }

    @Override
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void cleanExpiredTokens() {
        List<QrToken> expiredTokens = qrTokenRepository.findByExpireTimeBefore(LocalDateTime.now());
        qrTokenRepository.deleteAll(expiredTokens);
    }
}